<template>
	<view>
		<web-view :src="fileUrl"></web-view>
	</view>
</template>

<script>
	import config from '@/config'
	import {
		encode
	} from '@/utils/js-base64.js'
	import { getCoursewareDetail, coursewareLearn } from '@/api/studyGarden/index.js'
	
	export default {
		data() {
			return {
				id: '',
				title: '',
				fileUrl: '',
				timeCount: 0,
				timeCountTimer: null,
				
				autoSaveTimer: null,
				autoSaveTime: 30 // 单位秒
			}
		},
		onLoad(params) {
			if (params.id) {
				this.id = params.id
				this.getDetail()
			}
		},
		onShow() {
			if (this.fileUrl) {
				this.startTime()
			}
		},
		onHide() {
			this.saveTime()
		},
		beforeDestroy() {
			this.saveTime()
			clearInterval(this.autoSaveTimer)
		},
		methods: {
			getDetail() {
				getCoursewareDetail(this.id).then(res => {
					if (res.data.fileUrl) {
						const url = res.data.fileUrl
						let _url = url.replace('/minio//', '/minio/')
						this.fileUrl =
							`${config.staticUrl}/file-view/onlinePreview?url=${encodeURIComponent(encode(_url))}&officePreviewType=pdf`
						this.startTime()
					} else {
						uni.showToast({
							title: '文件地址错误',
							icon: 'none'
						})
					}
				})
			},
			startTime() {
				if (this.timeCountTimer) {
					return
				}
				this.timeCount = 0;
				clearInterval(this.timeCountTimer)
				this.timeCountTimer = setInterval(() => {
					++this.timeCount
				}, 1000);

				// 定时上传进度
				this.autoSaveTimer = setInterval(() => {
					this.saveTime()
					this.startTime()
				}, this.autoSaveTime * 1000);
			},
			saveTime() {
				clearInterval(this.timeCountTimer)
				this.timeCountTimer = null
				clearInterval(this.autoSaveTimer)
				this.autoSaveTimer = null
				coursewareLearn({
					coursewareId: this.id,
					learnedDuration: this.timeCount,
					showLoading: false
				}).then(() => {
					console.log('时长保存成功');
					this.timeCount = 0
				})
			}
		}
	}
</script>

<style>
</style>